#include <iostream>
#include <sys/types.h>
#include <cstring>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
// #include <signal.h>
#include <arpa/inet.h>
#include "Comm.hpp"

#define Retry_Count 5

void Usage(std::string str)
{
    std::cout << "Usage: " << str << "local_ip local_port" << std::endl;
}

bool visitServer(std::string &serverip, uint16_t &serverport, int *cnt)
{
     std::string inbuffer;
    // 1.创建套接字
    int socked = socket(AF_INET, SOCK_STREAM, 0);
    if (socked < 0)
    {
        std::cerr << "socket error" << std::endl;
        return socket_err;
    }
    bool ret = true;
    // 2.connect
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;                          // 网络套接字类型
    server.sin_port = htons(serverport);                  // 将主机端口转换成网络序列
    server.sin_addr.s_addr = inet_addr(serverip.c_str()); // 将字符串ip转换成网络序列ip

    int n = connect(socked, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        ret = false;
        goto END;
    }
    *cnt = 0;
   
    std::cout << "Please select:";
    std::getline(std::cin, inbuffer);
    write(socked, inbuffer.c_str(), inbuffer.size());
    while (true)
    {
        
        //std::string inbuffer;
        std::cout << "Please enter:";
        std::getline(std::cin, inbuffer);
        if (inbuffer == "quit")
            break;
        ssize_t n = write(socked, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buffer[1024];
            ssize_t m = read(socked, buffer, sizeof(buffer) - 1);

            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "get message->" << buffer << std::endl;
            }
            else if (m == 0)
            {
                break;
            }
            else
            {
                ret = false;
                goto END;
            }
        }
        else
        {
            ret = false;
            goto END;
        }
    }
END:
    close(socked);
    return ret;
}



int main(int argc, char **argv)
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return usage_err;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int cnt = 0;
    while (cnt <= Retry_Count)
    {
        bool result = visitServer(serverip, serverport, &cnt);
        if (result)
        {
            break;
        }
        else
        {
            sleep(1);
            std::cout << "sever offline,retrying...,count:" << cnt << std::endl;
            cnt++;
        }
    }

    if (cnt >= Retry_Count)
    {
        std::cout << "sever offline" << std::endl;
    }
    return 0;
}